package com.charlotte.study.gupao.flyweight.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

/**
 * @author junjie.ding
 * @date 2020/3/10
 */
public class ConnectionPool {

    private Vector<Connection> pool;

    private String url = "jdbc:mysql://localhost:3306/test";

    private final String username = "root";

    private final String password = "123456";

    private final String driverName = "com.mysql.jdbc.Driver";


    public ConnectionPool() {
        pool = new Vector<>(100);

        try {
            Class<?> aClass = Class.forName(driverName);
            for (int i = 0; i < 100; i++) {
                Connection connection = DriverManager.getConnection(url, username, password);
                pool.add(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized Connection getConnection(){
        if(pool.size() > 0){
            Connection connection = pool.remove(0);
            return connection;
        }
        return null;
    }

    public synchronized void releaseConn(Connection connection){
        pool.add(connection);
    }
}
